package cn.kgc.count.service;

import cn.kgc.common.entity.Article;
import cn.kgc.count.dao.CountDao;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.websocket.server.ServerEndpoint;
import java.util.*;

/**
 * Created by teacher ZHANG on 2022/12/1
 */
@Service
public class CountServiceImpl implements CountService {
    @Autowired
    private CountDao countDao;
    //PV(访问量)
    //UV(独立访客)
    @Value("${article.uv.key}")
    private String uvKey;
    @Value("${article.sort.key}")
    private String sortKey;

    @Override
    public Integer addAddress(Integer articleId, String address) {
        countDao.hyperLogAdd(uvKey + articleId, address);
        return countDao.hyperLogCount(uvKey + articleId);
    }

    //定时器中执行此函数
    @Override
    @Scheduled(fixedRate = 5000)
    public void sortVisitorNum() {
        //取所有浏览量的key值
        Set<String> keys = countDao.keys("uv-*");
        for (String key : keys) {
            //取每一篇文章的浏览量
            Integer num = countDao.hyperLogCount(key);

            //取文章的ID
            String aid = key.substring(key.lastIndexOf("-")+1);
            //加入有序集合中
            countDao.zsetAdd(sortKey, aid, num);
        }
    }

    @Override
    public List<Map<String, Integer>> listByVisitors(Integer num) {

        List<Map<String, Integer>> result = new ArrayList<>();

        //转换有序集合的返回值
        List<Map<String, Integer>> list = countDao.zsetRevrange(sortKey, num);
        for (Map<String, Integer> map : list) {
            Integer articleId = map.get("value");
            Integer visitorNum = map.get("score");
            Map<String, Integer> item = new HashMap<>();
            item.put("articleId", articleId);
            item.put("visitorNum", visitorNum);

            result.add(item);
        }

        return result;
    }

    @Override
    public List<Map<String, Integer>> listCounts(List<Integer> idList) {
        List<Map<String, Integer>> maps = new ArrayList<>();
        //取所有文章的浏览量
        for (Integer articleId : idList) {
            String key = uvKey + articleId;

            Integer count = countDao.hyperLogCount(key);

            Map<String, Integer> map = new HashMap<>();
            map.put("articleId", articleId);
            map.put("visitorNum", count);

            maps.add(map);
        }

        return maps;
    }


}
